package com.lagou.sqlSession;

import com.lagou.config.BoundSql;
import com.lagou.pojo.Configuration;
import com.lagou.pojo.MappedStatement;
import com.lagou.utils.GenericTokenParser;
import com.lagou.utils.ParameterMapping;
import com.lagou.utils.ParameterMappingTokenHandler;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.List;

public class SimpleExecutor implements Executor {

    @Override
    public <T> List<T> query(Configuration configuration, MappedStatement mappedStatement, Object... params)
            throws Exception {
        // 1.获取数据库连接
        Connection connection = configuration.getDataSource().getConnection();

        // 2.获取sql语句
        String sql = mappedStatement.getSql();

        // 3.解析sql 将#{}解析为？
        BoundSql boundSql = this.getBoundSql(sql);

        //4.获取sql预处理对象
        PreparedStatement preparedStatement = connection.prepareStatement(boundSql.getSqlText());

        // 5. 设置参数
            //获取参数值类型
        String paramterType = mappedStatement.getParamterType();
        Class<?> paramterTypeClass = this.getTypeClass(paramterType);
        List<ParameterMapping> parameterMappingList = boundSql.getParameterMappingList();
        for (int i = 0; i < parameterMappingList.size(); i++) {
            ParameterMapping parameterMapping = parameterMappingList.get(i);
            String content = parameterMapping.getContent();
            //通过反射获取属性
            Field declaredField = paramterTypeClass.getDeclaredField(content);
            //防止变量为私有的，设置暴力访问
            declaredField.setAccessible(true);
            Object o = declaredField.get(params[0]);
            preparedStatement.setObject(i+1, o);
        }

        // 6.执行sql
        ResultSet resultSet = preparedStatement.executeQuery();
        String resultType = mappedStatement.getResultType();
        Class<?> resultTypeClass = this.getTypeClass(resultType);
        ArrayList<Object> objects = new ArrayList<>();

        // 7.封装返回结果集
        while(resultSet.next()){
            Object o =resultTypeClass.newInstance();
            //元数据
            ResultSetMetaData metaData = resultSet.getMetaData();
            for (int i = 1; i <= metaData.getColumnCount(); i++) {
                // 字段名
                String columnName = metaData.getColumnName(i);
                // 字段的值
                Object value = resultSet.getObject(columnName);
                //使用反射或者内省，根据数据库表和实体的对应关系，完成封装
                PropertyDescriptor propertyDescriptor = new PropertyDescriptor(columnName, resultTypeClass);
                Method writeMethod = propertyDescriptor.getWriteMethod();
                writeMethod.invoke(o,value);
            }
            objects.add(o);

        }
        return (List<T>) objects;
    }

    @Override
    public void execute(Configuration configuration, MappedStatement mappedStatement, Object... params) throws Exception {
        // 1.获取数据库连接
        Connection connection = configuration.getDataSource().getConnection();
        // 2.获取sql
        String sql = mappedStatement.getSql();
        // 3.解析sql
        BoundSql boundSql = this.getBoundSql(sql);
        // 4.获取sql预处理对象
        PreparedStatement preparedStatement = connection.prepareStatement(boundSql.getSqlText());
        // 5.获取参数类型及设置参数
        String paramterType = mappedStatement.getParamterType();
        Class<?> paramterTypeClass = this.getTypeClass(paramterType);
        List<ParameterMapping> parameterMappingList = boundSql.getParameterMappingList();
        for (int i = 0; i < parameterMappingList.size(); i++) {
            ParameterMapping parameterMapping = parameterMappingList.get(i);
            String content = parameterMapping.getContent();
            Field declaredField = paramterTypeClass.getDeclaredField(content);
            //设置暴力访问
            declaredField.setAccessible(true);
            Object o = declaredField.get(params[0]);
            preparedStatement.setObject(i + 1, o);
        }
        preparedStatement.execute();
    }
//
//    @Override
//    public void update(Configuration configuration, MappedStatement mappedStatement, Object... params) throws Exception {
//        //1.获取连接
//        Connection connection = configuration.getDataSource().getConnection();
//        //2.获取sql
//        String sql = mappedStatement.getSql();
//        //3.解析sql
//        BoundSql boundSql = this.getBoundSql(sql);
//        //4.获取预编译处理对象
//        PreparedStatement preparedStatement = connection.prepareStatement(boundSql.getSqlText());
//        //5.获取参数类型及设置参数
//        String paramterType = mappedStatement.getParamterType();
//        //6.根据反射获取类
//        Class<?> typeClass = this.getTypeClass(paramterType);
//        //7.获取解析完的sql参数集合
//        List<ParameterMapping> parameterMappingList = boundSql.getParameterMappingList();
//        //循环参数集合
//        for (int i = 0; i < parameterMappingList.size(); i++) {
//            ParameterMapping parameterMapping = parameterMappingList.get(i);
//            String content = parameterMapping.getContent();
//            Field declaredField = typeClass.getDeclaredField(content);
//            declaredField.setAccessible(true);
//            Object o = declaredField.get(params[0]);
//            preparedStatement.setObject(i+1,o);
//        }
//        preparedStatement.execute();
//    }
//
    @Override
    public void delete(Configuration configuration, MappedStatement mappedStatement, Object... params) throws Exception {
        //1.获取连接
        Connection connection = configuration.getDataSource().getConnection();
        //2.获取sql
        String sql = mappedStatement.getSql();
        //3.解析sql
        BoundSql boundSql = this.getBoundSql(sql);
        //4.获取预发布sql
        PreparedStatement preparedStatement = connection.prepareStatement(boundSql.getSqlText());
        //5.获取及设置参数
        String paramterType = mappedStatement.getParamterType();
        //6.通过反射获取参数类
        Class<?> typeClass = this.getTypeClass(paramterType);
        //7.获取参数
        List<ParameterMapping> parameterMappingList = boundSql.getParameterMappingList();
        for (int i = 0; i < parameterMappingList.size(); i++) {
            ParameterMapping parameterMapping = parameterMappingList.get(i);
            String content = parameterMapping.getContent();
            preparedStatement.setObject(i+1,content);
        }
        preparedStatement.execute();
    }

    /**
     * 根据路径获取类
     * @param paramterType
     * @return
     * @throws ClassNotFoundException
     */
    private Class<?> getTypeClass(String paramterType) throws ClassNotFoundException {
        if(paramterType != null){
            Class<?> aClass = Class.forName(paramterType);
            return aClass;
        }

        return null;
    }

    /**
     * 完成#{}的解析，1.先将 #{}使用?代替  2.解析出来#{}里面的值进行存储
     * @param sql
     * @return
     */
    private BoundSql getBoundSql(String sql) {
        //标记处理类：配置标记解析器完成对占位符的解析处理工作
        ParameterMappingTokenHandler parameterMappingTokenHandler = new ParameterMappingTokenHandler();
        GenericTokenParser genericTokenParser = new GenericTokenParser("#{", "}", parameterMappingTokenHandler);
        //解析出来的sql
        String sqlText = genericTokenParser.parse(sql);
        List<ParameterMapping> parameterMappings = parameterMappingTokenHandler.getParameterMappings();

        BoundSql boundSql = new BoundSql(sqlText,parameterMappings);
        return boundSql;

    }
}
